/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package hi.chyl.json;

import java.beans.PropertyChangeListener;
import java.util.List;
import java.util.Vector;
import java.util.concurrent.ExecutionException;
import org.apache.commons.httpclient.DefaultHttpMethodRetryHandler;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.methods.ByteArrayRequestEntity;
import org.apache.commons.httpclient.methods.PostMethod;
import org.jdesktop.swingworker.SwingWorker;
import org.openide.util.Exceptions;

/**
 *
 * @author chench
 */
public class RequestWorker extends SwingWorker<String, Void> {

    private String url;

    /**
     * Get the value of url
     *
     * @return the value of url
     */
    public String getUrl() {
        return url;
    }

    /**
     * Set the value of url
     *
     * @param url new value of url
     */
    public void setUrl(String url) {
        this.url = url;
    }
    private String data;

    /**
     * Get the value of data
     *
     * @return the value of data
     */
    public String getData() {
        return data;
    }

    /**
     * Set the value of data
     *
     * @param data new value of data
     */
    public void setData(String data) {
        this.data = data;
    }

    public RequestWorker(String url, String data) {
        this.url = url;
        this.data = data;
    }

    @Override
    protected String doInBackground() throws Exception {
        HttpClient client = new HttpClient();
        client.getHttpConnectionManager().getParams().setConnectionTimeout(0);
        client.getHttpConnectionManager().getParams().setSoTimeout(0);
        PostMethod method = new PostMethod(url);
        method.addRequestHeader("Content-Type", "application/x-www-form-urlencoded; charset=GB18030");
        method.addRequestHeader("Connection", "keep-alive");
        DefaultHttpMethodRetryHandler retry = new DefaultHttpMethodRetryHandler(0, false);
        org.apache.commons.httpclient.methods.RequestEntity objRequestEntity = new ByteArrayRequestEntity(data.getBytes());
        method.setRequestEntity(objRequestEntity);
        method.getParams().setParameter("http.method.retry-handler", retry);
        client.executeMethod(method);
        String resp = method.getResponseBodyAsString();
        return resp;
    }

    @Override
    protected void done() {
        try {
            String resp = get();
            System.out.println(resp);
        } catch (InterruptedException ex) {
            Exceptions.printStackTrace(ex);
        } catch (ExecutionException ex) {
            Exceptions.printStackTrace(ex);
        }
    }

    @Override
    protected void process(List<Void> list) {
        super.process(list);
    }
    
    
}
